<template>
  <div class="third-category-container">
    <div class="tool">
      <div class="left">
        <!-- 搜索字段类型 -->
        <el-tooltip
          effect="dark"
          content="请选择要搜索的字段名"
          placement="top"
          :manual="true"
          v-model="fieldTip"
        >
          <el-select
            clearable
            class="selectField"
            v-model="searchField"
            placeholder="搜索字段名"
            @change="changeField"
          >
            <el-option label="所属二级分类" value="sName"></el-option>
            <el-option label="三级分类名" value="tName"></el-option>
            <el-option label="创建时间" value="createTime"></el-option>
            <el-option label="更新时间" value="updateTime"></el-option>
          </el-select>
        </el-tooltip>

        <!-- 搜索框 -->
        <el-input
          clearable
          v-if="searchField !== 'createTime' && searchField !== 'updateTime'"
          class="searchInput"
          v-model="searchText"
          placeholder="请输入搜索文本"
          type="text"
          prefix-icon="el-icon-search"
          @keydown.enter.native="pagingSearch"
        ></el-input>

        <!-- 时间日期选择框 -->
        <el-date-picker
          v-else
          class="dateTimePicker"
          v-model="dateTimeInterval"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
        >
        </el-date-picker>

        <!-- 搜索按钮 -->
        <el-button type="info" @click="pagingSearch">搜索</el-button>
      </div>
    </div>

    <!-- 表格数据 -->
    <el-table
      v-loading="tableLoading"
      stripe
      empty-text
      :data="thirdCategoryList"
      @selection-change="currentSelect = $event"
    >
      <el-table-column align="center" type="selection" width="55">
      </el-table-column>
      <el-table-column
        type="index"
        width="50"
        label="序号"
        align="center"
      ></el-table-column>

      <el-table-column
        align="center"
        prop="sName"
        label="所属二级分类"
      ></el-table-column>
      <el-table-column
        align="center"
        prop="tName"
        label="三级分类名"
      ></el-table-column>
      <el-table-column
        width="100px"
        align="center"
        prop="sort"
        label="排序"
        sortable
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="createTime"
        label="创建时间"
        :formatter="formatDateTime"
      ></el-table-column>
      <el-table-column
        align="center"
        sortable
        prop="updateTime"
        label="更新时间"
        :formatter="formatDateTime"
      ></el-table-column>
      <el-table-column align="center" label="操作" class-name="operation">
        <template slot-scope="scope">
          <span class="security">编辑</span>
          <span class="danger" @click="deleteThirdCategory(scope.row)"
            >删除</span
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页查询 -->
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalPage"
    >
    </el-pagination>
  </div>
</template>

<script>
import { pagingQuery, deleteThirdCategory } from "@/api/thirdCategory";
import { mapState } from "vuex";

export default {
  name: "ThirdCategoryIndex",
  components: {},
  props: {},
  data() {
    return {
      fieldTip: false, // 是否显示 选择字段的提示
      searchField: "", // 搜索字段
      searchText: "", // 搜索文本
      dateTimeInterval: null, // 日期时间间隔
      pickerOptions: {
        // 设置时间选择器快捷方法
        shortcuts: [
          {
            text: "最近一天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      tableLoading: true, // 表格加载状态
      thirdCategoryList: [], // 三级分类列表
      currentSelect: [], // 当前多选框被选中了的数据
      page: 2, // 默认查询页码
      pageSize: 10, // 默认查询一页数量
      totalPage: 0, // 数据的总页数
    };
  },
  created() {
    // 加载三级分类列表
    if (this.user) {
      this.pagingQuery();
    }
  },
  mounted() {},
  methods: {
    // 改变搜索字段调用该方法
    changeField(field) {
      if (field !== "createTime" && field !== "updateTime") {
        this.dateTimeInterval = null;
      } else {
        this.searchText = "";
      }
    },
    // 分页展示数据
    async pagingQuery() {
      // 1. 打开表格加载状态
      this.tableLoading = true;
      // 2. 发送请求获取数据
      try {
        const { data } = await pagingQuery({
          searchField: this.searchField,
          searchText: this.searchText,
          startDateTime: this.dateTimeInterval
            ? new Date(this.dateTimeInterval[0])
            : null,
          endDateTime: this.dateTimeInterval
            ? new Date(this.dateTimeInterval[1])
            : null,
          page: this.page,
          pageSize: this.pageSize,
        });
        this.thirdCategoryList = data.data.records;
        this.totalPage = data.data.total;
      } catch (err) {
        console.log(err);
        this.$message.error("获取数据失败，请稍后重试");
      } finally {
        this.tableLoading = false;
      }
    },
    // 页码改变时触发该方法
    handleCurrentChange(page) {
      this.tableLoading = true;
      this.page = page;
      this.pagingQuery();
    },
    // 一页显示数据量变化时触发该方法
    handleSizeChange(pageSize) {
      this.tableLoading = true;
      this.pageSize = pageSize;
      this.pagingQuery();
    },
    // 格式化时间的显示
    formatDateTime(row, tableItem) {
      const prop = tableItem.property;
      if (prop === "createTime") {
        return this.format(row.createTime);
      } else if (prop === "updateTime") {
        return this.format(row.updateTime);
      } else {
        return "暂无数据";
      }
    },
    // 格式化时间方法
    format(dateTime) {
      if (dateTime) {
        let date = new Date(dateTime);
        let year = date.getFullYear();
        let month = this.fillZero(date.getMonth() + 1); //月份是从0开始的
        let day = this.fillZero(date.getDate());
        let hour = this.fillZero(date.getHours());
        let min = this.fillZero(date.getMinutes());
        let sec = this.fillZero(date.getSeconds());
        let formatTime =
          year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;
        return formatTime;
      } else {
        return "暂无数据";
      }
    },
    // 时间补零方法
    fillZero(value) {
      if (value < 10) {
        return "0" + value;
      }
      return value;
    },
    // 删除三级分类
    deleteThirdCategory(row) {
      const tId = row.tId;
      const tName = row.tName;
      this.$confirm(`您确定要删除 ${tName} 三级分类吗？`, {
        type: "warning",
        showClose: false,
        closeOnClickModal: false,
      })
        .then(async () => {
          try {
            // 传给后端要修改的状态
            const { data } = await deleteThirdCategory(tId);
            if (data.code === 200) {
              this.$message.success("删除三级分类成功");
              // this.loadThirdCategoryList();
            } else {
              this.$message.error(data.msg);
            }
          } catch (err) {
            this.$message.error("删除三级分类失败");
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 搜索
    pagingSearch() {
      // 1. 判断搜索字段或搜索关键字是否为空
      if (this.searchText.length > 0 && this.searchField.length === 0) {
        // 1.1 搜索字段为空,搜索文本不为空
        this.fieldTip = true;
        return setTimeout(() => {
          this.fieldTip = false;
        }, 2000);
      } else if (this.searchField.length > 0 && this.searchText.length === 0 && this.dateTimeInterval === null) {
        // 1.2 字段不为空，搜索文本为空和时间为null
        this.$message.info("请输入搜索的文本或选择时间");
      } else {
        // 1.3 都为空
        this.page = 1;
        this.pagingQuery();
      }
    },
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {},
};
</script>

<style scoped lang="less">
.third-category-container {
  :deep(.tool) {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    .selectField {
      margin-right: 20px;
      width: 150px;
    }

    .searchInput {
      margin-right: 20px;
      width: 250px;
      .el-icon-search {
        cursor: pointer;
      }
    }
    .dateTimePicker {
      margin-right: 20px;
    }
  }

  :deep(.el-table) {
    border: solid 2px #f3f4f7;
    .el-table__header-wrapper {
      .el-table__header {
        .cell {
          font-size: 13px;
          color: #666;
        }
      }
    }

    .el-table__body-wrapper {
      color: #333;
      font-size: 12px;
      .el-table__body {
        .el-table__row:hover {
          background-color: #fcfcf5 !important;
        }
        .operation {
          .cell {
            display: flex;
            justify-content: space-evenly;
            align-items: center;
            span {
              cursor: pointer;
            }
            span.security {
              color: #419eff !important;
            }
            span.danger {
              color: #f56c6c !important;
            }
          }
        }
      }
    }
  }

  .el-pagination {
    text-align: center;
    margin-top: 55px;
  }
}
</style>
